﻿using System;
using System.Diagnostics;
using System.DirectoryServices;
using System.IO;
using CommandLineParser.Arguments;
using uTILLIty.ADExtractor.Core;
using uTILLIty.ADExtractor.Core.Exporters.Sql;
using uTILLIty.ADExtractor.Core.Extensions;
using uTILLIty.ADExtractor.Properties;

namespace uTILLIty.ADExtractor
{
	internal class SqlExportCommand : ExportCommandBase
	{

		[FileArgument('i', "input", Description = "The config XML", Example = "-i template.xml", FileMustExist = true, Optional = false,
			FullDescription = "See the provided sample configuration files for reference")]
		public FileInfo ConfigFile;

		[ValueArgument(typeof(string),'d', "db", Description = "An overriding database connection-string", Optional = true,
			Example = "-d \"Data Source=.;Initial Catalog=master;Integrated Security=True\"")]
		public string DbConnectionString;

		protected override bool Export(QueryInformation query, SearchResultCollection result)
		{
			var exporter = new SqlExporter { DontWarnUndeclaredParameters = Silent };
			if (Silent)
				exporter.LogMessage += (o, e) => Console.WriteLine(e.Message);
			else
				exporter.LogMessage += (o, e) => Console.WriteLine(Resources.LogMessageOutput, e.Severity, e.Message);

			SqlExporterConfiguration config;
			using (var stream = ConfigFile.OpenRead())
			{
				config = ObjectExtensions.Load<SqlExporterConfiguration>(stream, null);
			}
			if (!string.IsNullOrEmpty(DbConnectionString))
				config.ConnectionString = DbConnectionString;

			exporter.Export(query, result, config);
			return true;
		}

		public override string GetAdditionalHelpText()
		{
			var exporter = new SqlExporter { DontWarnUndeclaredParameters = Silent };

			FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(typeof(Program).Assembly.Location);
			var help = string.Format(Resources.SimpleUsageExample, Path.GetFileName(fileInfo.FileName),
													 "SQL -i sql.xml -q \"(&(objectCategory=User)(initials=*))\" -f objectSID,displayName,Manager:manager.samAccountName,count(memberof)");
			help += string.Format(Resources.KnownSqlProviders, exporter.GetRegisteredDbProviders());
			return help;
		}

	}
}